﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Collections;
namespace Littlebeer.Deduplicate.Functions
{
    public class Similar : IDeduplicateFunction
    {
        public string DoFunction(object input, List<string> args)
        {
            string result=string.Empty;
            decimal MiniSimilar = Convert.ToDecimal(args[0]);
            Hashtable inputvalues = input as Hashtable;

            var query = from a in inputvalues.Cast<DictionaryEntry>().AsParallel()
                        join b in inputvalues.Cast<DictionaryEntry>().AsParallel() on 1 equals 1
                        where a.Key != b.Key && GetSimilarRate(a.Value.ToString(), b.Value.ToString()) >= MiniSimilar
                        select new { id1 = a.Key, id2 = b.Key };
            result = string.Join(",", query.Select(d => d.id1).Union(query.Select(d => d.id2)));
            return result;
        }
        public decimal GetSimilarRate(string querystr, string targetstr)
        {
            decimal sr = 0;
            decimal Kq = 1;
            decimal Kr = 1;
            decimal Ks = 1;

            char[] ss = querystr.ToCharArray();
            char[] st = targetstr.ToCharArray();

            //获取交集数量
            int q = ss.Intersect(st).Count();
            int s = ss.Length - q;
            int r = st.Length - q;
            sr= Kq * q / (Kq * q + Kr * r + Ks * s);
            return sr;
        }
    }
}
